import request from '@/utils/request'
import type { User } from '@/types'
import { mockLogin, mockLogout, mockGetUserInfo } from '@/mock/auth'
import { mockUserAPI } from '@/mock/api'

// 是否启用Mock模式
const ENABLE_MOCK = import.meta.env.VITE_ENABLE_MOCK !== 'false'

// 登录
export const login = (data: { username: string; password: string }) => {
  if (ENABLE_MOCK) {
    return mockLogin(data.username, data.password)
  }
  return request({
    url: '/auth/login',
    method: 'post',
    data
  })
}

// 登出
export const logout = () => {
  if (ENABLE_MOCK) {
    return mockLogout()
  }
  return request({
    url: '/auth/logout',
    method: 'post'
  })
}

// 获取用户信息
export const getUserInfo = () => {
  if (ENABLE_MOCK) {
    const token = localStorage.getItem('token') || ''
    return mockGetUserInfo(token)
  }
  return request({
    url: '/auth/info',
    method: 'get'
  })
}

// 获取用户列表
export const getUserList = (params: any) => {
  if (ENABLE_MOCK) {
    return mockUserAPI.getList(params)
  }
  return request({
    url: '/user/list',
    method: 'get',
    params
  })
}

// 创建用户
export const createUser = (data: Partial<User>) => {
  if (ENABLE_MOCK) {
    return mockUserAPI.create(data)
  }
  return request({
    url: '/user',
    method: 'post',
    data
  })
}

// 更新用户
export const updateUser = (id: string, data: Partial<User>) => {
  if (ENABLE_MOCK) {
    return mockUserAPI.update(id, data)
  }
  return request({
    url: `/user/${id}`,
    method: 'put',
    data
  })
}

// 删除用户
export const deleteUser = (id: string) => {
  if (ENABLE_MOCK) {
    return mockUserAPI.delete(id)
  }
  return request({
    url: `/user/${id}`,
    method: 'delete'
  })
}

// 重置密码
export const resetPassword = (id: string, password: string) => {
  return request({
    url: `/user/${id}/password`,
    method: 'put',
    data: { password }
  })
}
